<?php
class mysql_DbModel{
	protected $_columns = null;//表的字段属性
    protected $_primaryKey = 'id';
	protected $_sql=null;
	protected $_table=null;//表名称
	protected $_field='*';
	protected $_count=0;
	public function __construct(){
		
	}
	//表的字段属性
	public function columns(){
		return $this->query("SHOW COLUMNS FROM ".$this->_table);	
	}
	//返回db对象
	static public function getInstance(){
		static $db=null;
		if(!$db){
			$conf = new Yaf_Config_Ini(ROOT_PATH . '/conf/db.ini','common');
			$prefix=$conf->db->prefix;//数据表前缀
			Yaf_Registry::set('db_prefix',$prefix);
			$db = new mysql_DbModel();	
		}
		return $db;
	}
	//返回pdo实例
	static public function db_getInstance(){
		static $pdo_db=null;
		if(!$pdo_db){
			$conf = new Yaf_Config_Ini(ROOT_PATH . '/conf/db.ini','common');
			if(!$conf){
				throw new Exception('数据库连接必须设置');
			}
			
			$user=$conf->db->user;
		
			$pwd=$conf->db->pwd;
			$host=$conf->db->host;
			$charset=$conf->db->charset;
			$name=$conf->db->name;
			$type=$conf->db->type;
			
			
			
			$dsn=$type.':host='.$host.';dbname='.$name.';charset='.$charset;			
			$pdo_db = new PDO($dsn,$user,$pwd);	
			$pdo_db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);//PDO异常模式
			$pdo_db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);//关闭预处理模拟
		}
		return $pdo_db;
	}
	//where 条件
	public function where($arr){
		if(is_array($arr)){
			//数组解析
		}
		$str=$arr;unset($arr);
		$this->_sql['_where']=$str;
		return self::getInstance();
	}
	//limit 条件
	public function limit($n1,$n2=""){
		$n1=intval($n1);
		if($n1>0){
			$this->_sql['_limit']='LIMIT '.$n1;				
			if(!$n2){	
				$n2=intval($n2);
				if($n2>0){			
					$this->_sql['_limit'].=','.$n2;
				}
			}
		}
		return self::getInstance();
	}
	//选取table
	public function M($table){
		if(!$table){
			throw new Exception('没有选择数据表');
		}
		$pre=Yaf_Registry::get('db_prefix');
	
		$this->_table=$pre.$table;
		return self::getInstance();
	}
	//查询字段名
	public function field($field=""){
		if(is_array($field) && !empty($field)){
			$field=	implode(',',$field);
		}
		if($field){
			$this->_field=$field;
		}
		return self::getInstance();
	}
	//order 条件
	public function order($str){
		$this->_sql['_order']="ORDER BY ".$str;
	}

	//qruey 查询
	public function query($sql){
		if($sql==""){
			return false;
		}
		$data=self::db_getInstance()->query($sql);	
		
		$this->_count=$data->rowCount();
	
		if($this->_count==1){
			$result = $data->fetch(PDO::FETCH_ASSOC);
		}else if($this->_count>1){
			$result = $data->fetchAll(PDO::FETCH_ASSOC);
		}else{
			$result=false;
		}
		
		return $result;
	}
	
	//update 语句
	public function save($arr){
		if(!is_array($arr) && emtpy($arr)){
			return false;	
		}
		$this->_sql['_save']='';
		foreach($arr as $k=>$v){
			$v=$this->parseValue($v);
			$this->_sql['_save'].= '`'.$k.'`='.$v.',';
		}
		$this->_sql['_save']=rtrim($this->_sql['_save'],',');	
		unset($arr);
		$sql='UPDATE '.$this->_table.' SET '.$this->_sql['_save'];
		if(isset($this->_sql['_where']) && $this->_sql['_where']!=""){
			$sql .=' WHERE '.$this->_sql['_where'];
		}
		return $this->execute($sql);
	}
	
	
	

	//分析$v
    protected function parseValue($value) {
        if(is_string($value)) {
            $value =  '\''.$this->addslashes($value).'\'';
        }elseif(isset($value[0]) && is_string($value[0]) && strtolower($value[0]) == 'exp'){
            $value =  $this->addslashes($value[1]);
        }elseif(is_array($value)) {
            $value =  array_map(array($this, 'parseValue'),$value);
        }elseif(is_bool($value)){
            $value =  $value ? '1' : '0';
        }elseif(is_null($value)){
            $value =  'null';
        }
        return $value;
    }
	
	//添加语句
	public function add($arr){
		if(!is_array($arr) && emtpy($arr)){
			return false;	
		}
		$this->_sql['_add']='';
		$k_str ='(';
		foreach($arr as $k=>$v){
			$v=$this->parseValue($v);
			$k_str .='`'.$k.'`,';
			$v_str.= $v.',';
		}
		$k_str=rtrim($k_str,',');
		$v_str=rtrim($v_str,',');
		$this->_sql['_add']=$k_str .') VALUES (' .$v_str . ')';
		unset($arr);
		$sql='INSERT INTO '.$this->_table.' '.$this->_sql['_add'];	
		
		return $this->execute($sql);
		
	}
	
	//执行语句
	public function execute($sql){
		if($sql==""){
			return false;
		}
		try{
			$num=self::db_getInstance()->exec($sql);
			if($num===0){
				return false;
			}else{	
				return self::db_getInstance()->lastInsertId();					
			}
		}catch(PDOException $e){
			return false;
		}
	}
	//查询多条返回
	public function select(){			
		$sql='SELECT '.$this->_field.' FROM '.$this->_table;
		if(isset($this->_sql['_where']) && $this->_sql['_where']!=""){
			$sql .=' WHERE '.$this->_sql['_where'];
		}
		if(isset($this->_sql['_limit']) && $this->_sql['_limit']!=""){
				$sql.=' '.$this->_sql['_limit'];
		}
		if(isset($this->_sql['_order']) && $this->_sql['_order']!=""){
				$sql.=' '.$this->_sql['_order'];
		}
		//返回pdo 对象
		return $this->query($sql);
	}
	//查询总条数
	public function count(){
		$sql='SELECT COUNT(*) AS yaf_count FROM '.$this->_table;
		if(isset($this->_sql['_where']) && $this->_sql['_where']!=""){
			$sql .=' WHERE '.$this->_sql['_where'];
		}
		//返回pdo 对象		
		$data=$this->query($sql);
		$yaf_count=($data["yaf_count"])?intval($data["yaf_count"]):0;
		return $yaf_count;
	}
	
	//查询最新一条返回
	public function find(){
		$this->_sql['_limit']='LIMIT 1';
		return $this->select();
	}
}